from django.utils.safestring import mark_safe
class Pagination():
    def __init__(self,request,queryset,page_param='page',page_size=10,page_plus=5):
        '''
        page_param:页码参数
        page_size:每页记录数
        page_plus:当前页前后的页数
        '''
        self.query_dict = request.GET
        self.query_dict._mutable=True
        self.queryset = queryset

        #获取当前页
        page_str = request.GET.get(page_param,'1')
        if page_str.isdecimal():
            page = int(page_str)
        else:
            page = 1
        self.page = page

        self.page_param = page_param
        #每页记录数
        self.page_size = page_size
        self.page_plus = page_plus

        #总记录数
        self.totals = self.queryset.count()

        #总页数
        p,div = divmod(self.totals,self.page_size)
        if div:
            p+=1
        self.pages = p

        #验证当前页有效性
        if self.page < 1:
            self.page = 1
        if self.pages >0 and self.page > self.pages:
            self.page = self.pages
        print('__init__',self.page)
    def get_page_result(self):
        '''获取当前页数据'''
        print('self.page=',self.page)
        start = (self.page -1 ) * self.page_size
        end = self.page * self.page_size
        print('分页start=',start,' end=',end)
        return self.queryset[start:end]

    def get_page_str(self):
        '''获取分页html片段'''

        #计算开始页与结束页
        start_page = self.page-self.page_plus
        end_page = self.page + self.page_plus
        if start_page < 1:
            start_page = 1
        if end_page > self.pages:
            end_page = self.pages

        page_str = '<ul class="pagination">'
        self.query_dict.setlist(self.page_param, [1])
        page_str+='<li><a href="?{}">首页</a></li>'.format(self.query_dict.urlencode())
        self.query_dict.setlist(self.page_param, [self.page-1])
        page_str+='<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())
        for p in range(start_page,end_page+1):
            class_name = ''
            if p == self.page:
                class_name = 'active'
            self.query_dict.setlist(self.page_param, [p])
            page_str+='<li class="{}"><a href="?{}">{}</a></li>'.format(class_name,self.query_dict.urlencode(),p)

        self.query_dict.setlist(self.page_param, [self.page+1])
        page_str+='<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode())
        self.query_dict.setlist(self.page_param, [self.pages])
        page_str+='<li><a href="?{}">末页</a></li>'.format(self.query_dict.urlencode())
        page_str+='</ul>'
        page_str = mark_safe(page_str)
        return page_str